﻿using Common;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using T68Control.View;
using License = Common.License;

namespace T68Control
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        #region 异常处理函数

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Mylog.Error((e.ExceptionObject as Exception).InnerException, "未知的异常[CurrentDomain_UnhandledException]");
        }

        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            e.SetObserved();
            Mylog.Error(e.Exception, "未知的异常[TaskScheduler_UnobservedTaskException]");
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            Mylog.Error(e.Exception, "未知的异常[App_DispatcherUnhandledException]");
            e.Handled = true;
        }

        #endregion 异常处理函数

        private Mutex mutex;
        private string msg;

        protected override void OnStartup(StartupEventArgs e)
        {
            bool ret;
            mutex = new Mutex(true, "PCBATest", out ret);
            if (!ret)
            {
                System.Windows.MessageBox.Show("程序已运行");
                //Environment.Exit(0);
                Current.Shutdown();
            }

            //#region 异常处理

            DispatcherUnhandledException += App_DispatcherUnhandledException;

            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            base.OnStartup(e);
            //#endregion 异常处理
            string sn = "";
            try
            {
                sn = License.GetSN(Environment.CurrentDirectory + "/license.sn");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            if (License.Check(out msg))
            {
                var loginView = new LoginView();
                var loginResult = loginView.ShowDialog();
                if (loginResult == true)
                {
                    loginView.Close();
                    new MainView(msg, sn).Show();
                }
            }
            else
            {
                MessageBox.Show("设备序列号校验异常");
                Environment.Exit(0);
            }
        }
    }
}